import java.util.ArrayList;
import java.util.List;

public class RoundRobinScheduler {
    public static void roundRobinSchedule(List<PCB> processes, int timeSlice) {
        //实现了时间片轮转调度算法
        List<PCB> finishList = new ArrayList<>();
        int currentTime = 0;
        while (!processes.isEmpty()) {
            PCB current = processes.get(0);
            current.state = "运行";
            //进程剩余时间小于等于时间片，则运行完毕
            if (current.remainTime <= timeSlice) {
                current.cpuTime += current.remainTime;
                current.remainTime = 0;
                current.finishTime = currentTime + current.allTime;
                currentTime = current.finishTime;
                current.state = "结束";
                finishList.add(current);
                processes.remove(current);
            } else {//更新时间属性后重新加入进程列表末尾，进程时间剩余时间大于时间片
                current.cpuTime += timeSlice;
                current.remainTime -= timeSlice;
                currentTime += timeSlice;
                processes.remove(current);
                processes.add(current);
            }
            printProcessInfo(processes, currentTime);
        }
        printMetrics(finishList);
    }

    private static void printProcessInfo(List<PCB> processes, int currentTime) {
        System.out.println("当前时间: " + currentTime);
        System.out.println("进程ID\t优先级\t已用CPU时间\t总需时间\t剩余时间\t状态");
        for (PCB p : processes) {
            System.out.println(p.id + "\t\t" + p.priority + "\t\t" + p.cpuTime + "\t\t" + p.allTime + "\t\t" + p.remainTime + "\t\t" + p.state);
        }
    }

    private static void printMetrics(List<PCB> processes) {
        double totalTurnaroundTime = 0;
        for (PCB p : processes) {
            double turnaroundTime = p.finishTime;
            totalTurnaroundTime += turnaroundTime;
        }
        double averageTurnaroundTime = totalTurnaroundTime / processes.size();
        System.out.println("平均周转时间: " + averageTurnaroundTime);
    }
}
